import {computed, designComponent, onMounted, PropType, reactive, useRefs, watch} from "plain-design-composition";
import React from "react";
import {MicroApp, MicroUtils, Page} from "plain-micro-application";

export const MicroNavigationPageSingleCase = designComponent({
    props: {
        app: {type: Object as PropType<MicroApp>, required: true},
        page: {type: Object as PropType<Page | null>, required: true},
    },
    setup({props}) {

        const {refs, onRef} = useRefs({el: HTMLDivElement})

        const isShow = computed(() => !!props.page)

        const wrapperElAttrs = computed(() => {
            const attrs = {} as any
            !!props.page && (attrs['data-page-path'] = props.page.path)
            attrs.style = {}
            attrs.style.display = isShow.value ? '' : 'none'
            attrs['data-single-app'] = "target"
            return attrs
        })

        const state = reactive({
            onShowPage: (page: Page) => {/*default callback*/},
        })

        onMounted(async () => {
            const loader = props.app.loader || props.app.config.loader
            await loader!({
                el: refs.el!,
                page: null as any,
                tab: null as any,
                nav: null as any,
                onBack: null as any,
                entryPublicPath: MicroUtils.EntryApplicationPublicPathConfigure.get(),
                onShowPage: (callback) => {state.onShowPage = callback}
            })

            /**
             * 当page变化的时候，调用单例子应用的showPage动作
             * @author  韦胜健
             * @date    2022/1/10 17:42
             */
            watch(() => props.page, async (page) => {
                if (!page) {return}
                await state.onShowPage(page)
            }, {immediate: true})
        })

        return () => (
            <div
                className="micro-navigator-page"
                ref={onRef.el}
                {...wrapperElAttrs.value}
            />
        )
    },
})
